<template>
    <nly-content-wrapper style="overflow-x:hidden;">
        <nly-content-header>
            <nly-row class="ml-1 mb-2" style="font-size:80%;">
                <nly-breadcrumb :item="breadcrumbItem" />
            </nly-row>
            <nly-container fluid>
                <nly-row class="ml-1 mb-2 lr">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;">
                        <form-input name="name" title="模块名称" rightStyle="width:120px;" id="name" labelStyle class="ml-2" v-show="show" v-model="postData.moduleName"></form-input>
                        <!-- <form-select
              title="状态"
              style="height: 28px"
              rightClass="col"
              v-model="postData.status"
              :dataList="[
                { key: 1, title: '正常' },
                { key: 0, title: '停用' }
              ]"
            ></form-select> -->
                    </nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button size="sm" variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
                            <nly-button size="sm" variant="info" @click="AddModule" button-class="mr-2">添加</nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row>
            </nly-container>
        </nly-content-header>
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" :data-source="data" bordered :pagination="pagination" style="font-size: 12px;" @change="onTableChange">
                <template slot="treeSort" slot-scope="text, record">
                    <editable-cell :text="text" @editableChange="onCellChange(record,'treeSort',$event)" :reg="numberReg" />
                </template>
            </a-table>
            <!-- 模块弹窗  -->
            <a-modal :visible="editModal" lg :footer="null" :title="editItem.id ? '编辑模块' : '新增模块'" size="xl" @cancel="handleReset">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" @submit="handleSubmit">
                        <a-row :gutter="24">
                            <a-col :span="12" key="1">
                                <a-form-item label="模块名称">
                                    <a-input v-decorator="['moduleName', { rules: [{ required: true, message: '模块名称不能为空' }] }]" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" key="2">
                                <a-form-item label="模块编码">
                                    <a-input v-decorator="['moduleCode', { rules: [{ required: true, message: '模块编码不能为空' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24" key="3">
                            <a-col :span="12">
                                <a-form-item label="主类全名">
                                    <a-input v-decorator="['mainClassName', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" key="4">
                                <a-form-item label="版本">
                                    <a-input v-decorator="['currentVersion', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12" key>
                                <a-form-item label="描述">
                                    <a-textarea placeholder="请输入模块描述" :rows="6" v-decorator="['description', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24" :style="{ textAlign: 'right' }">
                                <a-button type="primary" html-type="submit">保存</a-button>
                                <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                                <a-button :style="{ marginLeft: '8px' }" @click="handleReset">关闭</a-button>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { FormInput, EditableCell } from "@/components/Form";
import { PageList, saveSysModule, deleteSysModule } from "@/api/module";
import { constantRouterComponentsKeys } from "@/router/generator-routers";
import { listToMap } from "../../../utils/tool/map";

export default {
    components: {
        FormInput,
        EditableCell
    },
    data () {
        const columns = [
            {
                title: "模块名称",
                dataIndex: "moduleName",
                key: "moduleName",
                width: 100
            },
            {
                title: "模块编码",
                dataIndex: "moduleCode",
                key: "moduleCode",
                width: 80
            },
            {
                title: "模块描述",
                dataIndex: "description",
                key: "description",
                width: 80
            },
            {
                title: "版本",
                dataIndex: "currentVersion",
                key: "currentVersion",
                width: 80
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: 80,
                customRender: (text, row, index) => {
                    return text == 2 ? (
                        <nly-badge bg-variant="danger">停用</nly-badge>
                    ) : (
                        <nly-badge bg-variant="success">正常</nly-badge>
                    );
                }
            },
            {
                title: "操作",
                dataIndex: "o",
                width: 80,
                key: "o",
                customRender: (text, row, index) => {
                    return (
                        <div class="icons-list">
                            <a
                                href="javascript:;"
                                title="编辑模块"
                                class="mr-1"
                                onClick={() => this.showModal(row)}
                            >
                                <a-icon type="edit" theme="twoTone" />
                            </a>
                            {row.status == 1 ? (
                                <a
                                    href="javascript:;"
                                    title="启用模块"
                                    class="mr-1 "
                                    onClick={() => this.updateModule(row)}
                                >
                                    <a-icon
                                        type="check-circle"
                                        theme="twoTone"
                                        two-tone-color="#52c41a"
                                    />
                                </a>
                            ) : (
                                <a
                                    href="javascript:;"
                                    title="禁用模块"
                                    class="mr-1 "
                                    onClick={() => this.updateModule(row)}
                                >
                                    <a-icon type="stop" theme="twoTone" two-tone-color="red" />
                                </a>
                            )}
                            <a
                                href="javascript:;"
                                title="删除模块"
                                class="mr-1 "
                                onClick={() => this.deleteSysModule(row)}
                            >
                                <a-icon
                                    type="delete"
                                    theme="twoTone"
                                    two-tone-color="#eb2f96"
                                />
                            </a>
                        </div>
                    );
                }
            }
        ];

        const breadcrumbItem = [
            {
                text: "首页",
                to: "/",
                icon: "nlyfont nly-icon-home-fill"
            },
            {
                text: "系统管理",
                to: "/system/menu"
            },
            {
                text: "模块管理",
                to: "/system/model/list",
                active: true
            }
        ];
        return {
            formLayout: "horizontal",
            expand: false,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            postData: {
                "page.current": 1,
                "page.size": 20,
                moduleName: "",
                status: ""
            },
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            columns,
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            breadcrumbItem, //导航栏
            show: true, //是否显示弹窗
            editItem: {}, //新增/编辑对象
            moduleList: [], //所有模块
            TreeSortEditList: new Map() //菜单排序修改集合
        };
    },
    mounted () {
        this.PageList();
    },
    computed: {
        parentMenu: function () {
            const map = new Map();
            map.set(this.editItem.parentId, "");
            return map;
        },
        moudelsMap: function () {
            return listToMap(this.moduleList, {
                key: "moduleCode",
                value: "moduleName"
            });
        },
        componentSelectList: function () {
            const dataList = new Array();
            constantRouterComponentsKeys().forEach(item => {
                dataList.push({ key: item, title: item });
            });
            return dataList;
        }
    },
    methods: {
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "page.size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageList();
        },
        //添加
        AddModule () {
            this.editItem = {};
            this.editModal = true;
        },
        //删除
        deleteSysModule (menu) {
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该模块吗？',
                onOk () {
                    deleteSysModule({ id: menu.id })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");

                                //刷新 列表
                                _this.PageList();
                            }
                        })
                },
                onCancel () {
                },
            });
        },
        //停用/启用模块
        updateModule (module) {
            let msg = module.status == 0 ? "停用" : "启用";
            let _this = this;
            this.$confirm({
                title: '提示',
                content: "您确定要" + msg + "该模块吗？",
                onOk () {
                    saveSysModule({ id: module.id, moduleCode: module.moduleCode, status: module.status == 1 ? 0 : 1 })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success(msg + "成功")
                                //刷新 列表
                                _this.PageList();
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        // 获取模块列表
        PageList () {
            const { postData } = this;
            PageList(postData)
                .then(response => {
                    console.log("获取菜单列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.data = records;
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        //获取 系统模块
        showFunction () {
            this.show = !this.show;
        },
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        moduleName: this.$form.createFormField({
                            value: this.editItem.moduleName
                        }),
                        moduleCode: this.$form.createFormField({
                            value: this.editItem.moduleCode
                        }),
                        mainClassName: this.$form.createFormField({
                            value: this.editItem.mainClassName
                        }),
                        currentVersion: this.$form.createFormField({
                            value: this.editItem.currentVersion
                        }),
                        description: this.$form.createFormField({
                            value: this.editItem.description
                        }),
                        id: this.$form.createFormField({
                            value: this.editItem.id
                        }),
                    };
                },
            });
            this.editModal = true;
        },
        hideModal () {
            this.editModal = false;
        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                "page.current": pagination.current,
                "page.size": pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        handleSubmit (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                console.log("开始保存:", this.editItem);
                let id = this.editItem.id;
                this.editItem = { ...values };
                this.editItem.id = id;
                if (!err) {
                    saveSysModule(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageList();
                                this.hideModal();
                            }
                        })

                }
            });
        },
        handleReset () {
            this.form.resetFields();
        },

        toggle () {
            this.expand = !this.expand;
        }
    }
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
</style>
